import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

// StatefulWidget 是真正的组件本体，用于接收外部传入的数据
class StatefullCase extends StatefulWidget {
  // 出于性能优化考虑，组件都推荐添加 const 保持组件不可变性
  const StatefullCase({super.key, this.title = "状态管理"});
  // 定义一个属性，用于接收外部传入的数据
  final String title;

  @override
  // _StatefullCaseState createState() => _StatefullCaseState();
  //生命周期 --创建
  createState() => _StatefullCaseState();
}

// state 是组件的状态类，单独管理组件的状态，UI，更新，生命周期
class _StatefullCaseState extends State<StatefullCase> {
  int count = 0;
  List channeList = [];

  @override
  void initState() {
    // 生命周期 --初始化 ，同鸿蒙的aboutToAppear
    super.initState();
    //初始化状态
    count = 100;
    //组件初始化时调用
    getChanneList();
  }

  void getChanneList() async {
    final dio = Dio();
    final res = await dio.get('https://geek.itheima.net/v1_0/channels');
    setState(() {
      channeList = res.data['data']['channels']; //需要更新UI
    });
    print(res.data['data']['channels']);
  }

  @override
  void dispose() {
    // 生命周期 --销毁 ，同鸿蒙的aboutToDisappear
    super.dispose();
    //组件销毁时调用
  }

  @override
  //生命周期 build --构建，同鸿蒙
  Widget build(BuildContext context) {
    // print("组件的build被调用了");
    return Center(
      child: Column(
        children: [
          Text('父传子数据：${widget.title}'),
          ElevatedButton(
              onPressed: () {
                setState(() {
                  count++;
                });
              },
              child: Text('点击+1 --- $count')),
          Expanded(
            flex: 1,
            child: ListView.builder(
              itemBuilder: (context, index) {
                return Container(
                  width: double.infinity,
                  height: 100,
                  margin:
                      const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                  color: Colors.green,
                  child: Text(channeList[index]['name']),
                );
              },
              itemCount: channeList.length,
            ),
          )
        ],
      ),
    );
  }
}
